package com.zzyl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.entity.CountByTime;
import com.zzyl.entity.Reservation;
import com.zzyl.mapper.CustomerReservationMapper;
import com.zzyl.service.CustomerReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.ReservationVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@Service
public class CustomerReservationServiceImpl implements CustomerReservationService {

    @Autowired
    private CustomerReservationMapper customerReservationMapper;
    @Override
    public Integer findCancellerCount() {
        Long id = UserThreadLocal.getUserId();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime star = LocalDateTime.of(now.toLocalDate(), LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(now.toLocalDate(), LocalTime.MAX);
        Integer count = customerReservationMapper.select(id,star,end);
        return count;
    }

    @Override
    public PageResponse<ReservationVo> findByPage(Integer status, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Long id = UserThreadLocal.getUserId();
        Page<Reservation> reservations = customerReservationMapper.selectByPage(status,id);
        PageResponse<ReservationVo> response = PageResponse.of(reservations, ReservationVo.class);
        return response;
    }

    @Override
    public void save(Reservation reservation) {
        reservation.setStatus(0);
        customerReservationMapper.insert(reservation);
    }

    @Override
    public void updateStatus(Long id) {
        customerReservationMapper.updateStatus(id);
    }

    @Override
    public List<CountByTime> selectCountByTime(LocalDateTime begin,LocalDateTime end) {
        List<CountByTime> list = customerReservationMapper.selectCountByTime(begin,end);
        while (begin.isBefore(end) || begin.isEqual(end)){
            CountByTime countByTime = new CountByTime(begin, 6);
            for (CountByTime countVO : list) {
                if (countVO.getTime().equals(begin)){
                    countByTime.setCount(countVO.getCount());
                    break;
                }
            }
            list.add(countByTime);
        }
        return list;
    }

    @Override
    public void updateAllStatus() {
        LocalDateTime time = LocalDateTime.now();
        customerReservationMapper.updateAllStatus(time);
    }
}
